package org.easyframework.beans.factory.support;

import org.easyframework.beans.BeanDefinition;
import org.easyframework.beans.factory.BeanCreationException;
import org.easyframework.beans.factory.BeanFactory;
import org.easyframework.util.ClassUtils;

import java.util.concurrent.ConcurrentHashMap;

public class DefaultBeanFactory implements BeanFactory,BeanDefinitionRegistry{

    private final ConcurrentHashMap<String,BeanDefinition> beanDefinitionMap= new ConcurrentHashMap<String,BeanDefinition>(64);

    private ClassLoader classLoader;

    @Override
    public Object getBean(String beanId) {
        BeanDefinition bd = this.getBeanDefinition(beanId);
        if (bd==null){
            return null;
        }
        return this.createBean(bd);
    }

    private Object createBean(BeanDefinition bd){
        String beanClassName = bd.getBeanClassName();
        ClassLoader classLoader = this.getClassLoader();
        try {
            Class<?> clazz = classLoader.loadClass(beanClassName);
            return clazz.newInstance();
        } catch (Exception e) {
            throw new BeanCreationException("create bean for "+ beanClassName +" failed",e);
        }
    }

    public ClassLoader getClassLoader(){
        return this.classLoader!=null?this.classLoader: ClassUtils.getDefaultClassLoader();
    }

    @Override
    public void registerBeanDefinition(String beanId, BeanDefinition bd) {
        this.beanDefinitionMap.put(beanId,bd);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanId) {
        return this.beanDefinitionMap.get(beanId);
    }
}
